/*
 * 📏 AIOT智能学习桌 - 超声波坐姿监测系统
 *
 * 核心功能：
 * ✅ 超声波距离精确检测 (HC-SR04)
 * ✅ AI智能坐姿分析和评分
 * ✅ 智能语音提醒系统
 * ✅ 数据实时存储和历史记录
 * ✅ 微信小程序数据同步
 * ✅ 自适应学习和个性化建议
 *
 * 硬件配置：
 * - 超声波传感器: HC-SR04 (TRIG=GPIO28, ECHO=GPIO29)
 * - 蜂鸣器: GPIO42 (PWM控制)
 * - 语音模块: UART5通信
 * - WiFi模块: ESP8266
 * - 存储: EEPROM + 外部存储
 *
 * 作者: AIOT智能学习桌项目组
 * 版本: v2.0 智能增强版
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "posture_monitor.h"
#include "ai_analysis.h"
#include "voice_system.h"
#include "data_storage.h"
#include "wechat_integration.h"

// ========== 硬件配置 ==========
#define ULTRASONIC_TRIG_PIN 28 // 超声波触发引脚 (GPIO28)
#define ULTRASONIC_ECHO_PIN 29 // 超声波回响引脚 (GPIO29)
#define BUZZER_PIN 42          // 蜂鸣器引脚 (GPIO42)
#define VOICE_UART 5           // 语音模块UART
#define WIFI_UART 5            // WiFi模块UART

// ========== 坐姿监测参数 ==========
#define IDEAL_DISTANCE_MIN 30.0f    // 理想距离最小值(cm)
#define IDEAL_DISTANCE_MAX 50.0f    // 理想距离最大值(cm)
#define WARNING_DISTANCE_MIN 20.0f  // 警告距离最小值(cm)
#define WARNING_DISTANCE_MAX 70.0f  // 警告距离最大值(cm)
#define CRITICAL_DISTANCE_MIN 15.0f // 危险距离最小值(cm)
#define CRITICAL_DISTANCE_MAX 80.0f // 危险距离最大值(cm)

// ========== 时间控制参数 ==========
#define DETECTION_INTERVAL 3000   // 检测间隔(ms)
#define WARNING_INTERVAL 30000    // 警告间隔(ms)
#define DATA_SAVE_INTERVAL 300000 // 数据保存间隔(ms) - 5分钟
#define STABILITY_THRESHOLD 3     // 稳定性阈值(连续检测次数)

// ========== 数据结构定义 ==========

// 坐姿检测结果
typedef struct
{
  float distance;              // 检测距离
  PostureStatus status;        // 坐姿状态
  float score;                 // 坐姿得分(0-100)
  char ai_suggestion[256];     // AI建议
  char voice_message[512];     // 语音消息
  bool needs_warning;          // 是否需要警告
  bool needs_immediate_action; // 是否需要立即行动
  uint32_t timestamp;          // 时间戳
} PostureResult;

// 用户坐姿数据
typedef struct
{
  uint32_t user_id;          // 用户ID
  float height;              // 身高(cm)
  float preferred_distance;  // 偏好距离(cm)
  int age;                   // 年龄
  char learning_habits[128]; // 学习习惯
  float adaptation_factor;   // 适应因子
} UserProfile;

// 坐姿历史记录
typedef struct
{
  PostureResult records[MAX_HISTORY_RECORDS]; // 历史记录数组
  int current_index;                          // 当前索引
  int total_records;                          // 总记录数
  float average_score;                        // 平均得分
  int warning_count;                          // 警告次数
  uint32_t session_start_time;                // 会话开始时间
} PostureHistory;

// 智能分析引擎
typedef struct
{
  float trend_analysis[24];  // 24小时趋势分析
  float pattern_weights[10]; // 模式权重
  float learning_rate;       // 学习率
  bool adaptive_enabled;     // 自适应是否启用
  uint32_t total_sessions;   // 总会话数
} AIAnalysisEngine;

// ========== 全局变量 ==========
static PostureMonitorSystem g_monitor_system;
static PostureHistory g_posture_history;
static UserProfile g_user_profile;
static AIAnalysisEngine g_ai_engine;
static uint32_t g_last_detection_time = 0;
static uint32_t g_last_warning_time = 0;
static uint32_t g_last_save_time = 0;

// ========== 核心功能实现 ==========

/**
 * @brief 初始化坐姿监测系统
 * @return int 初始化结果 (0: 成功, -1: 失败)
 */
int posture_monitor_init(void)
{
  printf("📏 初始化超声波坐姿监测系统...\n");

  // 硬件初始化
  if (ultrasonic_hardware_init() != 0)
  {
    printf("❌ 超声波硬件初始化失败\n");
    return -1;
  }

  if (buzzer_init() != 0)
  {
    printf("❌ 蜂鸣器初始化失败\n");
    return -1;
  }

  if (voice_system_init() != 0)
  {
    printf("❌ 语音系统初始化失败\n");
    return -1;
  }

  if (wifi_communication_init() != 0)
  {
    printf("❌ WiFi通信初始化失败\n");
    return -1;
  }

  // 系统状态初始化
  memset(&g_monitor_system, 0, sizeof(g_monitor_system));
  memset(&g_posture_history, 0, sizeof(g_posture_history));
  memset(&g_user_profile, 0, sizeof(g_user_profile));
  memset(&g_ai_engine, 0, sizeof(g_ai_engine));

  // AI引擎初始化
  ai_analysis_engine_init(&g_ai_engine);

  // 加载用户配置文件
  load_user_profile(&g_user_profile);

  // 加载历史数据
  load_posture_history(&g_posture_history);

  // 系统自检
  if (system_self_test() != 0)
  {
    printf("❌ 系统自检失败\n");
    return -1;
  }

  printf("✅ 超声波坐姿监测系统初始化完成\n");
  return 0;
}

/**
 * @brief 主监测循环
 * @return int 执行结果
 */
int posture_monitor_loop(void)
{
  uint32_t current_time = get_system_time_ms();

  // 检查是否到达检测时间
  if (current_time - g_last_detection_time >= DETECTION_INTERVAL)
  {

    // 执行坐姿检测
    PostureResult result;
    if (perform_posture_detection(&result) == 0)
    {

      // AI智能分析
      enhance_analysis_with_ai(&result, &g_ai_engine, &g_user_profile);

      // 记录数据
      record_posture_data(&g_posture_history, &result);

      // 检查是否需要警告
      if (result.needs_warning && should_give_warning(current_time))
      {
        trigger_posture_warning(&result);
        g_last_warning_time = current_time;
      }

      // 更新系统状态
      update_system_status(&result);

      // 实时数据发送
      send_realtime_data_to_wechat(&result);
    }

    g_last_detection_time = current_time;
  }

  // 定期数据保存
  if (current_time - g_last_save_time >= DATA_SAVE_INTERVAL)
  {
    save_session_data(&g_posture_history, &g_user_profile);
    sync_data_with_wechat(&g_posture_history);
    g_last_save_time = current_time;
  }

  // 处理外部命令
  handle_external_commands();

  return 0;
}

/**
 * @brief 执行坐姿检测
 * @param result 检测结果输出
 * @return int 检测结果 (0: 成功, -1: 失败)
 */
int perform_posture_detection(PostureResult *result)
{
  if (!result)
    return -1;

  // 多次测量取平均值，提高精度
  float distances[5];
  int valid_measurements = 0;

  for (int i = 0; i < 5; i++)
  {
    float distance = measure_ultrasonic_distance();
    if (distance > 0 && distance < 300)
    { // 有效范围内
      distances[valid_measurements++] = distance;
    }
    delay_ms(50); // 短暂延时
  }

  if (valid_measurements < 3)
  {
    printf("⚠️ 测量数据不足，无法进行有效检测\n");
    return -1;
  }

  // 计算平均距离（去除极值）
  result->distance = calculate_filtered_average(distances, valid_measurements);
  result->timestamp = get_system_time_ms();

  // 基础坐姿分析
  result->status = analyze_basic_posture(result->distance);
  result->score = calculate_posture_score(result->distance, result->status);

  // 生成基础建议
  generate_basic_suggestion(result);

  printf("📏 检测距离: %.1fcm | 状态: %s | 得分: %.1f\n",
         result->distance, get_posture_status_string(result->status), result->score);

  return 0;
}

/**
 * @brief 测量超声波距离
 * @return float 距离值(cm)，-1表示测量失败
 */
float measure_ultrasonic_distance(void)
{
  // 发送触发脉冲
  gpio_set_output(ULTRASONIC_TRIG_PIN, 0);
  delay_us(2);
  gpio_set_output(ULTRASONIC_TRIG_PIN, 1);
  delay_us(10);
  gpio_set_output(ULTRASONIC_TRIG_PIN, 0);

  // 测量回响脉冲宽度
  uint32_t start_time = get_system_time_us();
  uint32_t timeout = start_time + 30000; // 30ms超时

  // 等待回响开始
  while (gpio_read_input(ULTRASONIC_ECHO_PIN) == 0)
  {
    if (get_system_time_us() > timeout)
    {
      return -1; // 超时
    }
  }

  uint32_t echo_start = get_system_time_us();

  // 等待回响结束
  while (gpio_read_input(ULTRASONIC_ECHO_PIN) == 1)
  {
    if (get_system_time_us() > timeout)
    {
      return -1; // 超时
    }
  }

  uint32_t echo_end = get_system_time_us();

  // 计算距离
  uint32_t duration = echo_end - echo_start;
  float distance = (duration * 0.034f) / 2.0f; // 声速343m/s

  return distance;
}

/**
 * @brief 计算过滤平均值（去除极值）
 * @param values 数值数组
 * @param count 数值个数
 * @return float 过滤后的平均值
 */
float calculate_filtered_average(float *values, int count)
{
  if (count <= 2)
  {
    // 数据太少，直接平均
    float sum = 0;
    for (int i = 0; i < count; i++)
    {
      sum += values[i];
    }
    return sum / count;
  }

  // 排序
  for (int i = 0; i < count - 1; i++)
  {
    for (int j = i + 1; j < count; j++)
    {
      if (values[i] > values[j])
      {
        float temp = values[i];
        values[i] = values[j];
        values[j] = temp;
      }
    }
  }

  // 去除最大值和最小值，计算中间值的平均
  float sum = 0;
  for (int i = 1; i < count - 1; i++)
  {
    sum += values[i];
  }

  return sum / (count - 2);
}

/**
 * @brief 基础坐姿分析
 * @param distance 测量距离
 * @return PostureStatus 坐姿状态
 */
PostureStatus analyze_basic_posture(float distance)
{
  if (distance < 0)
  {
    return POSTURE_UNKNOWN;
  }

  if (distance < CRITICAL_DISTANCE_MIN)
  {
    return POSTURE_CRITICAL_TOO_CLOSE;
  }
  else if (distance > CRITICAL_DISTANCE_MAX)
  {
    return POSTURE_CRITICAL_TOO_FAR;
  }
  else if (distance < WARNING_DISTANCE_MIN)
  {
    return POSTURE_TOO_CLOSE;
  }
  else if (distance > WARNING_DISTANCE_MAX)
  {
    return POSTURE_TOO_FAR;
  }
  else if (distance >= IDEAL_DISTANCE_MIN && distance <= IDEAL_DISTANCE_MAX)
  {
    return POSTURE_EXCELLENT;
  }
  else if (distance < IDEAL_DISTANCE_MIN)
  {
    return POSTURE_SLIGHTLY_CLOSE;
  }
  else
  {
    return POSTURE_SLIGHTLY_FAR;
  }
}

/**
 * @brief 计算坐姿得分
 * @param distance 距离
 * @param status 坐姿状态
 * @return float 得分(0-100)
 */
float calculate_posture_score(float distance, PostureStatus status)
{
  float base_score = 0;

  switch (status)
  {
  case POSTURE_EXCELLENT:
    // 在理想范围内，根据距离给出90-100分
    float ideal_center = (IDEAL_DISTANCE_MIN + IDEAL_DISTANCE_MAX) / 2;
    float deviation = fabs(distance - ideal_center);
    float max_deviation = (IDEAL_DISTANCE_MAX - IDEAL_DISTANCE_MIN) / 2;
    base_score = 90 + (1 - deviation / max_deviation) * 10;
    break;

  case POSTURE_SLIGHTLY_CLOSE:
  case POSTURE_SLIGHTLY_FAR:
    base_score = 70 + (1 - fabs(distance - IDEAL_DISTANCE_MIN) / 10) * 15;
    break;

  case POSTURE_TOO_CLOSE:
  case POSTURE_TOO_FAR:
    base_score = 40 + (1 - fabs(distance - WARNING_DISTANCE_MIN) / 20) * 25;
    break;

  case POSTURE_CRITICAL_TOO_CLOSE:
  case POSTURE_CRITICAL_TOO_FAR:
    base_score = 10 + (1 - fabs(distance - CRITICAL_DISTANCE_MIN) / 30) * 25;
    break;

  default:
    base_score = 0;
    break;
  }

  // 确保得分在0-100范围内
  if (base_score < 0)
    base_score = 0;
  if (base_score > 100)
    base_score = 100;

  return base_score;
}

/**
 * @brief 生成基础建议
 * @param result 检测结果
 */
void generate_basic_suggestion(PostureResult *result)
{
  switch (result->status)
  {
  case POSTURE_EXCELLENT:
    strcpy(result->ai_suggestion, "坐姿非常棒！请继续保持这种良好状态。");
    strcpy(result->voice_message, "坐姿优秀，继续保持！");
    result->needs_warning = false;
    break;

  case POSTURE_SLIGHTLY_CLOSE:
    strcpy(result->ai_suggestion, "距离稍微有点近，建议轻微向后调整座椅位置。");
    strcpy(result->voice_message, "请稍微向后调整一下座椅位置。");
    result->needs_warning = true;
    break;

  case POSTURE_SLIGHTLY_FAR:
    strcpy(result->ai_suggestion, "距离稍微有点远，建议轻微向前调整座椅位置。");
    strcpy(result->voice_message, "请稍微向前调整一下座椅位置。");
    result->needs_warning = true;
    break;

  case POSTURE_TOO_CLOSE:
    snprintf(result->ai_suggestion, sizeof(result->ai_suggestion),
             "距离过近（%.1fcm），请向后调整座椅，理想距离为%.0f-%.0fcm。长时间近距离用眼会影响视力健康。",
             result->distance, IDEAL_DISTANCE_MIN, IDEAL_DISTANCE_MAX);
    snprintf(result->voice_message, sizeof(result->voice_message),
             "距离过近，当前%.1f厘米，请向后调整座椅，保护视力健康。",
             result->distance);
    result->needs_warning = true;
    result->needs_immediate_action = false;
    break;

  case POSTURE_TOO_FAR:
    snprintf(result->ai_suggestion, sizeof(result->ai_suggestion),
             "距离过远（%.1fcm），请向前调整座椅，理想距离为%.0f-%.0fcm。合适的距离有助于提高学习效率。",
             result->distance, IDEAL_DISTANCE_MIN, IDEAL_DISTANCE_MAX);
    snprintf(result->voice_message, sizeof(result->voice_message),
             "距离过远，当前%.1f厘米，请向前调整座椅，找到最佳学习位置。",
             result->distance);
    result->needs_warning = true;
    result->needs_immediate_action = false;
    break;

  case POSTURE_CRITICAL_TOO_CLOSE:
    snprintf(result->ai_suggestion, sizeof(result->ai_suggestion),
             "⚠️ 危险：距离严重过近（%.1fcm）！请立即向后调整座椅。这种距离会严重损害视力！",
             result->distance);
    snprintf(result->voice_message, sizeof(result->voice_message),
             "警告！距离严重过近，当前%.1f厘米，请立即向后调整座椅！",
             result->distance);
    result->needs_warning = true;
    result->needs_immediate_action = true;
    break;

  case POSTURE_CRITICAL_TOO_FAR:
    snprintf(result->ai_suggestion, sizeof(result->ai_suggestion),
             "⚠️ 危险：距离严重过远（%.1fcm）！请立即向前调整座椅，这种距离会严重影响学习效果。",
             result->distance);
    snprintf(result->voice_message, sizeof(result->voice_message),
             "警告！距离严重过远，当前%.1f厘米，请立即向前调整座椅！",
             result->distance);
    result->needs_warning = true;
    result->needs_immediate_action = true;
    break;

  default:
    strcpy(result->ai_suggestion, "无法检测坐姿，请检查传感器状态。");
    strcpy(result->voice_message, "检测失败，请检查设备状态。");
    result->needs_warning = false;
    break;
  }
}

/**
 * @brief AI增强分析
 * @param result 检测结果
 * @param ai_engine AI引擎
 * @param user_profile 用户配置
 */
void enhance_analysis_with_ai(PostureResult *result, AIAnalysisEngine *ai_engine, UserProfile *user_profile)
{
  if (!result || !ai_engine || !user_profile)
    return;

  // 个性化距离调整
  float personalized_adjustment = calculate_personalized_adjustment(user_profile);
  float adjusted_score = result->score + personalized_adjustment;

  // 时间趋势分析
  float trend_factor = analyze_time_trend(ai_engine, result->timestamp);
  adjusted_score *= trend_factor;

  // 学习模式识别
  float pattern_factor = recognize_learning_pattern(ai_engine, result);
  adjusted_score *= pattern_factor;

  // 更新AI建议
  enhance_ai_suggestion(result, user_profile, adjusted_score);

  // 更新AI引擎学习数据
  update_ai_learning_data(ai_engine, result);

  // 限制得分范围
  result->score = fmax(0, fmin(100, adjusted_score));

  printf("🤖 AI增强分析: 原始%.1f → 调整%.1f | 趋势%.2f | 模式%.2f\n",
         result->score, adjusted_score, trend_factor, pattern_factor);
}

/**
 * @brief 计算个性化调整
 * @param user_profile 用户配置
 * @return float 调整值
 */
float calculate_personalized_adjustment(UserProfile *user_profile)
{
  float adjustment = 0;

  // 基于身高的调整
  if (user_profile->height > 0)
  {
    if (user_profile->height < 160)
    {
      adjustment += 5; // 较矮用户，距离稍近也可接受
    }
    else if (user_profile->height > 180)
    {
      adjustment -= 3; // 较高用户，需要稍远的距离
    }
  }

  // 基于年龄的调整
  if (user_profile->age > 0)
  {
    if (user_profile->age < 12)
    {
      adjustment += 8; // 儿童，更宽松的标准
    }
    else if (user_profile->age > 50)
    {
      adjustment += 3; // 中老年，稍微宽松
    }
  }

  // 基于学习习惯的调整
  if (strstr(user_profile->learning_habits, "short_sessions"))
  {
    adjustment += 2; // 短时间学习，标准可以稍微宽松
  }

  return adjustment * user_profile->adaptation_factor;
}

/**
 * @brief 分析时间趋势
 * @param ai_engine AI引擎
 * @param timestamp 时间戳
 * @return float 趋势因子
 */
float analyze_time_trend(AIAnalysisEngine *ai_engine, uint32_t timestamp)
{
  // 获取当前小时
  int current_hour = (timestamp / 3600000) % 24;

  // 基于历史数据分析该时间段的表现趋势
  float hour_performance = ai_engine->trend_analysis[current_hour];

  if (hour_performance > 0.8)
  {
    return 1.1f; // 通常表现好的时间段，给予奖励
  }
  else if (hour_performance < 0.5)
  {
    return 0.9f; // 通常表现差的时间段，稍微宽松
  }

  return 1.0f; // 默认不调整
}

/**
 * @brief 识别学习模式
 * @param ai_engine AI引擎
 * @param result 检测结果
 * @return float 模式因子
 */
float recognize_learning_pattern(AIAnalysisEngine *ai_engine, PostureResult *result)
{
  // 分析连续性
  static float last_distances[5] = {0};
  static int distance_index = 0;

  last_distances[distance_index] = result->distance;
  distance_index = (distance_index + 1) % 5;

  // 计算距离变化的标准差
  float variance = calculate_variance(last_distances, 5);

  if (variance < 2.0f)
  {
    return 1.05f; // 坐姿稳定，给予奖励
  }
  else if (variance > 8.0f)
  {
    return 0.95f; // 坐姿不稳定，稍微严格
  }

  return 1.0f;
}

/**
 * @brief 增强AI建议
 * @param result 检测结果
 * @param user_profile 用户配置
 * @param enhanced_score 增强得分
 */
void enhance_ai_suggestion(PostureResult *result, UserProfile *user_profile, float enhanced_score)
{
  char enhanced_suggestion[512];
  char enhanced_voice[512];

  // 基于用户特征个性化建议
  if (user_profile->age < 12)
  {
    snprintf(enhanced_suggestion, sizeof(enhanced_suggestion),
             "小朋友，%s 记住正确的坐姿对身体发育很重要哦！",
             result->ai_suggestion);
    snprintf(enhanced_voice, sizeof(enhanced_voice),
             "小朋友，%s",
             result->voice_message);
  }
  else if (user_profile->age > 50)
  {
    snprintf(enhanced_suggestion, sizeof(enhanced_suggestion),
             "%s 保持良好坐姿有助于缓解腰背疲劳。",
             result->ai_suggestion);
    snprintf(enhanced_voice, sizeof(enhanced_voice),
             "%s 注意保护腰背健康。",
             result->voice_message);
  }
  else
  {
    // 基于学习效率增强建议
    if (enhanced_score >= 90)
    {
      snprintf(enhanced_suggestion, sizeof(enhanced_suggestion),
               "%s 您的学习状态很棒，继续保持这种专注！",
               result->ai_suggestion);
    }
    else if (enhanced_score < 60)
    {
      snprintf(enhanced_suggestion, sizeof(enhanced_suggestion),
               "%s 建议您稍作休息，调整好状态后再继续学习。",
               result->ai_suggestion);
    }
    else
    {
      strcpy(enhanced_suggestion, result->ai_suggestion);
    }
    strcpy(enhanced_voice, result->voice_message);
  }

  // 更新结果
  strcpy(result->ai_suggestion, enhanced_suggestion);
  strcpy(result->voice_message, enhanced_voice);
}

/**
 * @brief 更新AI学习数据
 * @param ai_engine AI引擎
 * @param result 检测结果
 */
void update_ai_learning_data(AIAnalysisEngine *ai_engine, PostureResult *result)
{
  if (!ai_engine->adaptive_enabled)
    return;

  // 更新时间趋势
  int current_hour = (result->timestamp / 3600000) % 24;
  float normalized_score = result->score / 100.0f;

  // 使用滑动平均更新
  ai_engine->trend_analysis[current_hour] =
      ai_engine->trend_analysis[current_hour] * (1 - ai_engine->learning_rate) +
      normalized_score * ai_engine->learning_rate;

  // 更新模式权重
  update_pattern_weights(ai_engine, result);

  // 增加会话计数
  ai_engine->total_sessions++;
}

/**
 * @brief 触发坐姿警告
 * @param result 检测结果
 */
void trigger_posture_warning(PostureResult *result)
{
  printf("⚠️ 坐姿警告: %s\n", result->ai_suggestion);

  // 播放警告音
  if (result->needs_immediate_action)
  {
    play_critical_warning_sound();
  }
  else
  {
    play_warning_sound();
  }

  // 语音提醒
  speak_message(result->voice_message);

  // 发送警告到微信小程序
  send_warning_to_wechat(result);

  // 记录警告事件
  log_warning_event(result);
}

/**
 * @brief 判断是否应该给出警告
 * @param current_time 当前时间
 * @return bool 是否应该警告
 */
bool should_give_warning(uint32_t current_time)
{
  return (current_time - g_last_warning_time) >= WARNING_INTERVAL;
}

/**
 * @brief 记录坐姿数据
 * @param history 历史记录
 * @param result 检测结果
 */
void record_posture_data(PostureHistory *history, PostureResult *result)
{
  // 添加新记录
  history->records[history->current_index] = *result;
  history->current_index = (history->current_index + 1) % MAX_HISTORY_RECORDS;

  if (history->total_records < MAX_HISTORY_RECORDS)
  {
    history->total_records++;
  }

  // 更新统计数据
  update_statistics(history);

  printf("📊 记录数据: 距离%.1fcm, 得分%.1f, 平均%.1f\n",
         result->distance, result->score, history->average_score);
}

/**
 * @brief 更新统计数据
 * @param history 历史记录
 */
void update_statistics(PostureHistory *history)
{
  if (history->total_records == 0)
    return;

  float total_score = 0;
  int warning_count = 0;

  int records_to_process = (history->total_records < MAX_HISTORY_RECORDS) ? history->total_records : MAX_HISTORY_RECORDS;

  for (int i = 0; i < records_to_process; i++)
  {
    total_score += history->records[i].score;
    if (history->records[i].needs_warning)
    {
      warning_count++;
    }
  }

  history->average_score = total_score / records_to_process;
  history->warning_count = warning_count;
}

/**
 * @brief 保存会话数据
 * @param history 历史记录
 * @param user_profile 用户配置
 */
void save_session_data(PostureHistory *history, UserProfile *user_profile)
{
  printf("💾 保存会话数据...\n");

  // 保存到EEPROM
  save_to_eeprom(history, user_profile);

  // 保存到外部存储
  save_to_external_storage(history);

  // 生成会话报告
  generate_session_report(history);

  printf("✅ 会话数据保存完成\n");
}

/**
 * @brief 发送实时数据到微信
 * @param result 检测结果
 */
void send_realtime_data_to_wechat(PostureResult *result)
{
  char json_data[1024];

  snprintf(json_data, sizeof(json_data),
           "{"
           "\"type\":\"realtime_posture\","
           "\"distance\":%.1f,"
           "\"status\":\"%s\","
           "\"score\":%.1f,"
           "\"suggestion\":\"%s\","
           "\"timestamp\":%u,"
           "\"needs_warning\":%s"
           "}",
           result->distance,
           get_posture_status_string(result->status),
           result->score,
           result->ai_suggestion,
           result->timestamp,
           result->needs_warning ? "true" : "false");

  send_data_to_wechat(json_data);
}

/**
 * @brief 发送警告到微信
 * @param result 检测结果
 */
void send_warning_to_wechat(PostureResult *result)
{
  char json_data[1024];

  snprintf(json_data, sizeof(json_data),
           "{"
           "\"type\":\"posture_warning\","
           "\"distance\":%.1f,"
           "\"status\":\"%s\","
           "\"score\":%.1f,"
           "\"voice_message\":\"%s\","
           "\"ai_suggestion\":\"%s\","
           "\"critical\":%s,"
           "\"timestamp\":%u"
           "}",
           result->distance,
           get_posture_status_string(result->status),
           result->score,
           result->voice_message,
           result->ai_suggestion,
           result->needs_immediate_action ? "true" : "false",
           result->timestamp);

  send_data_to_wechat(json_data);
}

/**
 * @brief 同步数据到微信
 * @param history 历史记录
 */
void sync_data_with_wechat(PostureHistory *history)
{
  printf("📱 同步数据到微信小程序...\n");

  // 发送历史数据
  send_history_data_to_wechat(history);

  // 发送统计报告
  send_statistics_to_wechat(history);

  // 发送AI分析报告
  send_ai_analysis_to_wechat(history, &g_ai_engine, &g_user_profile);

  printf("✅ 数据同步完成\n");
}

/**
 * @brief 处理外部命令
 */
void handle_external_commands(void)
{
  // 检查串口命令
  if (uart_has_data(WIFI_UART))
  {
    char command[256];
    if (uart_read_line(WIFI_UART, command, sizeof(command)) > 0)
    {
      process_external_command(command);
    }
  }
}

/**
 * @brief 处理外部命令
 * @param command 命令字符串
 */
void process_external_command(const char *command)
{
  if (strncmp(command, "GET_STATUS", 10) == 0)
  {
    send_current_status_to_wechat();
  }
  else if (strncmp(command, "CALIBRATE", 9) == 0)
  {
    perform_distance_calibration();
  }
  else if (strncmp(command, "RESET_DATA", 10) == 0)
  {
    reset_all_data();
  }
  else if (strncmp(command, "SET_USER_PROFILE:", 17) == 0)
  {
    update_user_profile(command + 17);
  }
  else if (strncmp(command, "ENABLE_AI:", 10) == 0)
  {
    g_ai_engine.adaptive_enabled = (command[10] == '1');
  }

  printf("🔧 处理外部命令: %s\n", command);
}

/**
 * @brief 系统自检
 * @return int 自检结果
 */
int system_self_test(void)
{
  printf("🔍 系统自检中...\n");

  // 超声波传感器测试
  float test_distance = measure_ultrasonic_distance();
  if (test_distance < 0)
  {
    printf("❌ 超声波传感器自检失败\n");
    return -1;
  }

  // 蜂鸣器测试
  if (buzzer_test() != 0)
  {
    printf("❌ 蜂鸣器自检失败\n");
    return -1;
  }

  // 语音系统测试
  if (voice_system_test() != 0)
  {
    printf("❌ 语音系统自检失败\n");
    return -1;
  }

  // 存储系统测试
  if (storage_system_test() != 0)
  {
    printf("❌ 存储系统自检失败\n");
    return -1;
  }

  printf("✅ 系统自检通过\n");
  return 0;
}

/**
 * @brief 获取坐姿状态字符串
 * @param status 坐姿状态
 * @return const char* 状态字符串
 */
const char *get_posture_status_string(PostureStatus status)
{
  switch (status)
  {
  case POSTURE_EXCELLENT:
    return "优秀";
  case POSTURE_SLIGHTLY_CLOSE:
    return "稍近";
  case POSTURE_SLIGHTLY_FAR:
    return "稍远";
  case POSTURE_TOO_CLOSE:
    return "过近";
  case POSTURE_TOO_FAR:
    return "过远";
  case POSTURE_CRITICAL_TOO_CLOSE:
    return "危险过近";
  case POSTURE_CRITICAL_TOO_FAR:
    return "危险过远";
  case POSTURE_UNKNOWN:
    return "未知";
  default:
    return "错误";
  }
}

/**
 * @brief 计算方差
 * @param values 数值数组
 * @param count 数值个数
 * @return float 方差
 */
float calculate_variance(float *values, int count)
{
  if (count <= 1)
    return 0;

  float mean = 0;
  for (int i = 0; i < count; i++)
  {
    mean += values[i];
  }
  mean /= count;

  float variance = 0;
  for (int i = 0; i < count; i++)
  {
    float diff = values[i] - mean;
    variance += diff * diff;
  }
  variance /= count;

  return variance;
}

// ========== 模块清理 ==========

/**
 * @brief 清理坐姿监测系统
 */
void posture_monitor_cleanup(void)
{
  printf("🧹 清理坐姿监测系统...\n");

  // 保存最终数据
  save_session_data(&g_posture_history, &g_user_profile);

  // 发送最终报告
  send_final_report_to_wechat(&g_posture_history);

  // 清理硬件资源
  ultrasonic_cleanup();
  buzzer_cleanup();
  voice_system_cleanup();
  wifi_communication_cleanup();

  printf("✅ 坐姿监测系统清理完成\n");
}